<template>
  <div>
    <van-search v-model.trim="searchText" show-action label="商品" background="#f66" placeholder="请输入搜索关键词" @search="onSearch">
      <template #action>
        <div @click="$router.go(-1)">取消</div>
      </template>
    </van-search>

    <!-- 历史记录 -->
    <div class="history">
      <!-- 搜索记录标题 -->
      <div class="h-top">
        <div class="h-left">
          <van-icon name="search" size="30" color="#c6c6c6" />
          <span>历史记录</span>
        </div>
        <div class="h-right">
          <van-icon name="delete" size="30" color="#c6c6c6" @click="remove" />
        </div>
      </div>
      <!-- 搜索记录内容 -->
      <div class="h-bottom" v-if="searchHis.length>0">
        <div class="h-con" v-for="item in searchHis" :key="item" @click="$router.push({
          path:'/searchResult',
          query:{
            word:item
          }
        })">{{item}}</div>
      </div>
      <div class="kong" v-else>暂无搜索记录</div>
    </div>
  </div>
</template>

<script>
/* 
  缓存存取
  存取 数据 (缓存只能存字符串  存 JSON.stringify() 取 JSON.parse)
  取： 考虑第一次取 使用三目运算符，来判断 本地存储里面有没有数据，若有数据，则加枸杞转换为 数组，取出；若没有数据，则返回一个空对象
  存：先取 parse 变成数组 变量保存，操作变量，再将变量存回去

*/
export default {
  data () {
    return {
      searchText: '',
      searchHis: localStorage.getItem('searchHis') ? JSON.parse(localStorage.getItem('searchHis')) : []
    }
  },
  methods: {
    onSearch () {
      // 存
      let his = localStorage.getItem('searchHis') ? JSON.parse(localStorage.getItem('searchHis')) : []
      if (this.searchText !=='') {
        his.unshift(this.searchText)
        his = [... new Set(his)] // 数组 去重
        // 长度限制，只能显示5条
        if (his.length > 5) {
          his.length = 5
        } 
        // 进入搜所结果页
        // this.$router.push(`/searchResult/${this.searchText}`)
        this.$router.push({
          path:'/searchResult',
          query:{
            word:this.searchText
          }
        })
        localStorage.setItem('searchHis',JSON.stringify(his))
      }
    },
    remove(){
      // 点击清除购物车
      localStorage.removeItem('searchHis') // 清除本地存储
      this.searchHis = [] // 将 渲染的数组 重新赋值为 空
    }
  },
}
</script>


<style lang="scss" scoped>
.history {
  padding: 0 8px;
  .h-top {
    width: 100%;
    height: 40px;
    display: flex;
    border-bottom: 1px solid #c6c6c6;
    justify-content: space-between;
    align-items: center;
    .h-left {
      display: flex;
      align-items: center;
    }
  }
  .h-bottom {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .h-con {
      padding: 5px 10px;
      border-radius: 8px;
      background-color: #f3f5f7;
      color: #333;
      margin: 5px 15px;
      margin-left: 0;
    }
  }
}
.kong{
  margin-top: 10px;
}
</style>